package com.zy.utils

import com.zy.zlog.ZLog.e
import com.zy.zlog.ZLog.d
import android.app.Activity
import android.content.Context
import android.content.res.Configuration
import android.graphics.Rect
import android.view.View
import com.zy.zlog.ZLog
import com.zy.utils.ActivityUtils
import android.view.ViewParent

object ActivityUtils {
    private const val TAG = "ActivityUtils"

    /**
     * 返回当前屏幕是否为竖屏。
     *
     * @param context
     * @return 当且仅当当前屏幕为竖屏时返回true, 否则返回false。
     */
    fun isScreenOrientationPortrait(context: Context): Boolean {
        return context.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT
    }

    fun checkActivityDestroyed(context: Context?): Boolean {
        if (context is Activity) {
            val activity = context
            if (activity.isFinishing || activity.isDestroyed) {
                e(
                    TAG,
                    "getActivity() == null || getActivity().isFinishing() || getActivity().isDestroyed()"
                )
                return true
            }
        }
        return false
    }

    fun showViewTree(view: View) {
        d(TAG, "0 $view")
        var curr = view.parent
        var index = 1
        while (curr != null) {
            d(TAG, "$index $curr")
            index++
            curr = curr.parent
        }
    }

    @JvmStatic
    fun showViewTreeAndLocation(view: View) {
        d(TAG, "" + 0 + " " + getVisibleRect(view) + " " + view)
        var curr = view.parent
        var index = 1
        while (curr != null) {
            d(TAG, "" + index + " " + getVisibleRect(curr) + " " + curr)
            index++
            curr = curr.parent
        }
    }

    private fun getVisibleRect(viewParent: ViewParent): String {
        return if (viewParent is View) {
            getVisibleRect(viewParent as View)
        } else "[]"
    }

    private fun getVisibleRect(view: View): String {
        val localVisibleRect = Rect()
        view.getLocalVisibleRect(localVisibleRect)
        val globalVisibleRect = Rect()
        view.getGlobalVisibleRect(globalVisibleRect)
        return localVisibleRect.toString() + " " + globalVisibleRect + " [" + view.width + "," + view.height + "] [" + view.x + "," + view.y + "] [" + view.translationX + "," + view.translationY + "]"
    }
}